package com.winit.openapi.zhongtong;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.common.URL;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.command.GetByKeyCommand;
import com.winit.common.spi.context.CommandContext;
import com.winit.oms.spi.isp.ISPOrderPickUpMessageService;
import com.winit.oms.spi.isp.command.ISPOrderPickUpMessageCommand;
import com.winit.oms.spi.isp.vo.ISPOrderPickUpMessage;
import com.winit.openapi.chinapost.constants.ChinaPostMD5Util;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.util.Config;
import com.winit.openapi.util.ValidateUtil;
import com.winit.openapi.zhongtong.model.RequestZTMsg;
import com.winit.vms.spi.ConfigService;

@Controller
@RequestMapping(value = "/zhongTong")
public class IspZtPickupController{

    private static final Logger          logger = LoggerFactory.getLogger(IspZtPickupController.class);
    @Resource
    private ISPOrderPickUpMessageService iSPOrderPickUpMessageService;
    @Resource
    private ConfigService configService;
    @Resource
    private Config             config;
    @RequestMapping(value = "/API")
    @ResponseBody
    public String addZTWeigth(HttpServletRequest request) throws IOException {
        String inputJsonStr = IOUtils.toString(request.getInputStream(), "utf-8");
        if(inputJsonStr==null){
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        Map<String, String> map = URL.valueOf("?"+inputJsonStr).getParameters();
        this.validMap(map);
        String data = URLDecoder.decode(map.get("data"), "utf-8");
        String company_id = URLDecoder.decode(map.get("company_id"), "utf-8");
        String msg_type = URLDecoder.decode(map.get("msg_type"), "utf-8");
        String data_digest = URLDecoder.decode(map.get("data_digest"), "utf-8");
        //验证签名
        logger.info("API中通请求参数-----------》|data="+data+"|company_id="+company_id+"|msg_type="+msg_type+"|data_digest="+data_digest);
        RequestZTMsg requestZTMsg = new RequestZTMsg();
        requestZTMsg.setCompany_id(company_id);
        requestZTMsg.setData_digest(data_digest);
        requestZTMsg.setMsg_type(msg_type);
        requestZTMsg.setData(data);
        if(!config.isSignFlag()){
            String sign = this.verifySignature(requestZTMsg);
            if(sign!=null)return sign;
        }
        Object obj = JSONObject.parseObject(data);
        if (obj instanceof JSONObject) {
            JSONObject json = JSONObject.parseObject(data);
            ValidateUtil.validNotNull(json, "logisticsId");
            ValidateUtil.validMaxLength(json, "logisticsId", 50);
            ValidateUtil.validNotNull(json, "tradeOrderId");
            ValidateUtil.validMaxLength(json, "tradeOrderId", 32);
            ValidateUtil.validBigDecimal(json, "weight", true);
            ISPOrderPickUpMessageCommand command = new ISPOrderPickUpMessageCommand();
            CommandContext ctx = new CommandContext();
            ctx.setUsername("ZT_SYSTEM");
            ctx.setLanguage("zh_CN");
            command.setCtx(ctx);
            ISPOrderPickUpMessage ipm = new ISPOrderPickUpMessage();
            ipm.setPickupId(json.getString("tradeOrderId"));
            ipm.setCfmTotalWeight(json.getBigDecimal("weight"));
            command.setiSPOrderPickUpMessage(ipm);
            iSPOrderPickUpMessageService.update(command);
            logger.info("API中通请求成功，单号:"+json.getString("tradeOrderId")+",重量:"+json.getBigDecimal("weight"));
        }else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        
        return "{\"data\": \"911000000012\",\"msg\": \"接收成功\",\"status\": true}";
    }
    
    private void validMap(Map<String, String> map) {
        if(map.get("data")==null){
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "data");
        }if(map.get("company_id")==null){
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "company_id");
        }if(map.get("msg_type")==null){
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "msg_type");
        }if(map.get("data_digest")==null){
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "data_digest");
        }
    }

    private String verifySignature(RequestZTMsg requestZTMsg) {
        
      //获取数据库配置的秘钥
        GetByKeyCommand<String> command = new GetByKeyCommand<String>();
        command.setSearchKey("ISP_ZT_PICKUP_KEY");
        String ztKey = configService.getValue(command);
        
        //获取ZT发送数字签名
        String digestKey = requestZTMsg.getData_digest();
        //获取ZT消息内容
        String data = requestZTMsg.getData().toString();
        //进行MD5和BASE64加密
        String encryptionKey = ChinaPostMD5Util.getMd5AndBase64(data+ztKey);
        //如果密钥不相同,则抛出异常
        if(!encryptionKey.equals(digestKey))
        {
            logger.info("签名错误：ZT传入的签名：="+digestKey+"; 验签之后的签名 ="+encryptionKey +"; 秘钥是chinaKey="+ztKey);
            return "{\"data\": \"000000\",\"msg\": \"签名验证失败\",\"status\": false}";
        }
        return null;
        
    }

    
    public static void main(String[] args) throws UnsupportedEncodingException {
       Map<String, String> map = URL.valueOf("").getParameters();
       URLDecoder.decode(map.get("data"), "utf-8");
       URLDecoder.decode(map.get("company_id"), "utf-8");
       URLDecoder.decode(map.get("msg_type"), "utf-8");
       URLDecoder.decode(map.get("data_digest"), "utf-8");
    
    }

}
